import java.io.IOException;
import java.util.ArrayList;


public class DownloadFileList {
	boolean debug = true;
	private Client client;
	
	public  ArrayList<DownloadFile> list; //Lista que guarda os ficheiros a serem descarregados
	
	public DownloadFileList(Client client){
		this.client = client;
		list = new ArrayList<DownloadFile>();
		DownloadListThread lt = new DownloadListThread();
		lt.start();
	}
	
	public void addFile(DownloadFile d){
		list.add(d);
	}
	
	public DownloadFile fileExistsBySha(String sha){
		int i = 0;
		if(!list.isEmpty()){
			while(i<list.size())
			{
				if(list.get(i).getShaValue().equals(sha))
					return list.get(i);
				i++;
			}
		}
		return null;
	}
	
	public int getFileIndex(DownloadFile f){
		int i = 0;
		if(!list.isEmpty()){
			while(i<list.size())
			{
				if(list.contains(f))
					return i;
				i++;
			}
		}
		return -1;
	}
	
	public boolean hasSha(String sha){
		int i=0;
		for(; i<list.size(); i++)
		{
			if(list.get(i).getShaValue().equals(sha))
				return true;
		}
		return false;
	}

	
	class DownloadListThread extends Thread{

		public void run()
		{
			while(true)
			{
				if(!list.isEmpty())
				{
					int i=0;
					while(i<list.size()){
						DownloadFile df = list.get(i);
						
						if(df.allChunksReceived())
						{
							try {
								df.createFile();
								client.myFiles.put(df.getShaValue(), df.getFileObject());
								list.remove(i);
							} catch (IOException e) {
								System.out.println("Error! Could not create the file " + df.getFileObject().filename + "!");
								e.printStackTrace();
							}
						}
						else{
							try{
								if(df.chunksReceived() >= df.getChunks().length/2){
									df.setChunksReceived(-1);
									Thread.sleep(200);
									//int n = (int) (Math.random()*(df.chunks.length-1));
									int n=0;
									int j=10;
									String missing = "GET " + df.getShaValue() + " ";
									for(; n<df.getChunks().length; n++){
										if (df.getChunks()[n] == null){
											if(j==0) break;
											if (j==10) missing += n; 
											else missing += "," + n;
											j--;
										}
									}
										if(j <10)
											client.sendPacket(missing);
										Thread.sleep(50);
								}
							} catch (Exception e) {
									// TODO Auto-generated catch block
								}
							}
						}
						i++;
					}
				}
		}
	}
	
	

	}
